package com.inibb.app.util.upload;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;

public class FileExtensionValidationHandler implements FileHandler{
	private Properties fileConfig;


	public FileExtensionValidationHandler(Properties fileConfig) {
		super();
		this.fileConfig = fileConfig;
	}



	public ValidationResult handle(File file) {
		ValidationResult vr=new ValidationResult();
		List<String> typelist=getTypes("system.upload.fileExtension");
		if(typelist.indexOf(getFileExtension(file))==-1){
			vr.getErrors().put(file.getName(), "The file content type and file extension  don't consistent.");
		}
		return vr;
	}



	public String getFileExtension(File file){
		String fileName=file.getName();
		String extension= StringUtils.lowerCase(fileName.substring(fileName.lastIndexOf('.')));
		return extension;
	}

	public List<String> getTypes(String limitFileType){
		List<String> list=new ArrayList<String>();
		String limitType=fileConfig.getProperty(limitFileType);
		String[] limitTypes=limitType.split(",");
		for(int i=0;i<limitTypes.length;i++){
			list.add(limitTypes[i]);
		}
		return list;
	}


	public static void main(String[] args) {
		File file=new File("d:/fileupload.properties");
		Properties config=new Properties();
		config.setProperty("system.upload.fileExtension", ".jpg,.txt,.properties");
		ValidationResult result=new FileExtensionValidationHandler(config).handle(file);
		System.out.println(result.getErrors().get(file.getName()));
	}

}
